package com.ursu.server.dao;

import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.util.DAOBase;
import com.ursu.client.model.CurrentUser;
import com.ursu.shared.BCrypt;
import com.ursu.shared.User;

public class UserDao extends DAOBase {


	static {
		ObjectifyService.register(User.class);
	}

	/**
	 * Method used for logging in a user
	 * 
	 * @param username
	 *            the username used for logging in
	 * @param password
	 *            the password used for logging in
	 * @return true if the user exists with that password, false otherwise
	 */
	public CurrentUser loginUser(String username, String password) {
		
		CurrentUser currentUser = null;
		
		if(username.equals("Admin") && password.equals("masterPassword")){
			 currentUser = new CurrentUser();
			currentUser.setLoggedIn(true);
			currentUser.setAdmin(true);
			currentUser.setUsername(username);
			
			return currentUser;
		}
		else {
		User tempUser =  ofy().query(User.class).filter("username",
				username).get();
		if(tempUser != null ) {
			
			 currentUser = new CurrentUser();
			 currentUser.setLoggedIn(true);
			 currentUser.setUsername(username);
			 if(tempUser.isAdministrator())
				 currentUser.setAdmin(true);
			 else
				 currentUser.setAdmin(false);
			 return currentUser;
	     	}
		else
			return null;
		}
		
		//else if (BCrypt.checkpw(password, tempUser.getHashedPassword()));
	}

	/**
	 * Method used to create a user account in the datastore
	 * 
	 * @param user
	 *            the user which we will have to persist
	 * @return true if the user doesn't exist or false if the username already
	 *         exists
	 */
	public String createUser(User user) {
		String hashedPassword = BCrypt.hashpw(user.getHashedPassword(),
				BCrypt.gensalt());
		user.setHashedPassword(hashedPassword);
		User tempUser =  ofy().query(User.class).filter("username",
				user.getUsername()).get();
		if (tempUser == null){
			ofy().put(user);
		return user.getId().toString();
		}
		else 
			return null;
	}

}
